<template>
  <div class="main user-layout-register">
    <h3><span>注册</span></h3>
    <Form ref="formRegister" :model="form" :rules="formItemRules" id="formRegister">
      <FormItem prop="email">
        <Input
          size="large"
          type="email"
          placeholder="邮箱"
          v-model="form.email"
        ></Input>
      </FormItem>
      <FormItem prop="password">
        <Poptip
          placement="right-start"
          width="240"
          wordWrap
          trigger="focus"
          transfer
          v-model="state.passwordLevelChecked">
          <template slot="content">
            <div :class="['user-register', passwordLevelClass]">强度：<span>{{ passwordLevelName }}</span></div>
            <Progress :percent="state.percent" hide-info :stroke-color="passwordLevelColor "/>
            <div style="margin-top: 10px;">
              <span>请至少输入 6 个字符。请不要使用容易被猜到的密码。</span>
            </div>
          </template>
          <Input
            style="width: 368px"
            size="large"
            type="password"
            v-model="form.password"
            @click="handlePasswordInputClick"
            autocomplete="off"
            placeholder="至少6位密码，区分大小写"
          ></Input>
        </Poptip>
      </FormItem>

      <FormItem prop="passwordConfirm">
        <Input
          size="large"
          type="password"
          v-model="form.passwordConfirm"
          autocomplete="off"
          placeholder="确认密码"
        ></Input>
      </FormItem>

      <FormItem prop="mobile">
        <Input size="large" placeholder="11 位手机号">
        <Select slot="prepend" style="width: 80px" v-model="form.mobilePrefix">
          <Option value="+86">+86</Option>
          <Option value="+87">+87</Option>
        </Select>
        </Input>
      </FormItem>
      <Row :gutter="16">
        <Col class="gutter-row" :span="16">
        <FormItem prop="captcha">
          <Input prefix="ios-mail-outline" v-model="form.captcha" size="large" type="text" placeholder="验证码"></Input>
        </FormItem>
        </Col>
        <Col class="gutter-row" :span="8">
        <Button
          class="getCaptcha"
          size="large"
          :disabled="state.smsSendBtn"
          @click="getCaptcha"
          v-text="!state.smsSendBtn && '获取验证码'||(state.time+' s')"></Button>
        </Col>
      </Row>

      <FormItem>
        <Button
          size="large"
          type="primary"
          class="register-button"
          :loading="registerBtn"
          @click="handleSubmit"
          :disabled="registerBtn">注册
        </Button>
        <router-link class="login" :to="{ name: 'login' }">使用已有账户登录</router-link>
      </FormItem>

    </Form>
  </div>
</template>

<script>
import { mixinDevice } from '@/utils/mixin.js'
import { getSmsCaptcha } from '@/api/login'

const levelNames = {
  0: '低',
  1: '低',
  2: '中',
  3: '强'
}
const levelClass = {
  0: 'error',
  1: 'error',
  2: 'warning',
  3: 'success'
}
const levelColor = {
  0: '#ff0000',
  1: '#ff0000',
  2: '#ff7e05',
  3: '#52c41a'
}
export default {
  name: 'Register',
  components: {},
  mixins: [mixinDevice],
  data () {
    return {
      form: {
        email: '',
        password: '',
        passwordConfirm: '',
        mobile: '',
        mobilePrefix: '+86',
        captcha: ''
      },
      formItemRules: {
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '至少6位密码，区分大小写', trigger: 'blur', validator: this.handlePasswordLevel }
        ],
        passwordConfirm: [
          { required: true, trigger: 'blur', validator: this.handlePasswordCheck }
        ],
        captcha: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入正确的手机号', trigger: 'blur', validator: this.handlePhoneCheck }
        ]
      },
      state: {
        time: 60,
        smsSendBtn: false,
        passwordLevel: 0,
        passwordLevelChecked: false,
        percent: 10,
        progressColor: '#FF0000'
      },
      registerBtn: false
    }
  },
  computed: {
    passwordLevelClass () {
      return levelClass[this.state.passwordLevel]
    },
    passwordLevelName () {
      return levelNames[this.state.passwordLevel]
    },
    passwordLevelColor () {
      return levelColor[this.state.passwordLevel]
    }
  },
  methods: {
    handlePasswordLevel (rule, value, callback) {
      let level = 0

      // 判断这个字符串中有没有数字
      if (/[0-9]/.test(value)) {
        level++
      }
      // 判断字符串中有没有字母
      if (/[a-zA-Z]/.test(value)) {
        level++
      }
      // 判断字符串中有没有特殊符号
      if (/[^0-9a-zA-Z_]/.test(value)) {
        level++
      }
      this.state.passwordLevel = level
      this.state.percent = level * 30
      if (level >= 2) {
        if (level >= 3) {
          this.state.percent = 100
        }
        callback()
      } else {
        if (level === 0) {
          this.state.percent = 10
        }
        callback(new Error('密码强度不够'))
      }
    },

    handlePasswordCheck (rule, value, callback) {
      const password = this.form.password
      if (value === undefined) {
        callback(new Error('请输入密码'))
      }
      if (value && password && value.trim() !== password.trim()) {
        callback(new Error('两次密码不一致'))
      }
      callback()
    },

    handlePhoneCheck (rule, value, callback) {
      const reg = /^1\d{10}$/
      if (value !== '' && !reg.test(value)) {
        callback(new Error('手机号码格式不正确'))
      } else {
        callback()
      }
    },

    handlePasswordInputClick () {
      if (!this.isMobile()) {
        this.state.passwordLevelChecked = true
        return
      }
      this.state.passwordLevelChecked = false
    },

    handleSubmit () {
      const { state, $router } = this
      this.$refs['formRegister'].validate((valid) => {
        if (valid) {
          state.passwordLevelChecked = false
          $router.push({ name: 'registerResult', params: { ...this.form } })
        }
      })
    },

    getCaptcha () {
      const { state, $Message, form } = this
      this.$refs['formRegister'].validateField('mobile', (valid) => {
        console.log(valid)
        if (valid) {
          state.smsSendBtn = true
          const interval = window.setInterval(() => {
            if (state.time-- <= 0) {
              state.time = 60
              state.smsSendBtn = false
              window.clearInterval(interval)
            }
          }, 1000)

          const hide = $Message.loading('验证码发送中..', 0)

          getSmsCaptcha({ mobile: form.mobile }).then(res => {
            setTimeout(hide, 2500)
            $Message.success('验证码获取成功，您的验证码为：' + res.result.captcha)
          }).catch((e) => {
            setTimeout(hide, 1)
            clearInterval(interval)
            state.time = 60
            state.smsSendBtn = false
          })
        }
      }
      )
    }
  },
  watch: {
    'state.passwordLevel' (val) {
      console.log(val)
    }
  }
}
</script>
<style lang="less">
  .user-register {

    &.error {
      color: #ff0000;
    }

    &.warning {
      color: #ff7e05;
    }

    &.success {
      color: #52c41a;
    }

  }

  .user-layout-register {
    .ivu-input-group-addon:first-child {
      background-color: #fff;
    }
  }
</style>
<style lang="less" scoped>
  .user-layout-register {

    & > h3 {
      font-size: 16px;
      margin-bottom: 20px;
    }

    .getCaptcha {
      display: block;
      width: 100%;
      height: 40px;
    }

    .register-button {
      width: 50%;
    }

    .login {
      float: right;
      line-height: 40px;
    }
  }
</style>
